package managerService;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Vector;

import managerGUI.ProjectListModel;
import model.MyProperties;
import model.Project;
import model.Type;

public class ProjectService implements Service{
	private List<Project> projects;
	private List<Type> types;
	private ProjectListModel listModel;
	private Properties prop = MyProperties.getInstance().getProperties(); 
	private String projectXMLPath = prop.getProperty("xmloutproject");
	private String typeXMLPath = prop.getProperty("xmlouttype");
	
	public ProjectService(){
		projects = new ArrayList<Project>();
		types = new Vector<Type>();
	}
	
	public void setListModel(ProjectListModel model){
		this.listModel = model;
	}
	
	@Override
	public void addProject(Project p) {
		projects.add(p);
		listModel.refresh();
		p.toFile();
	}

	@Override
	public void addType(Type t) {
		types.add(t);
		t.toFile();
	}

	@Override
	public void removeProject(int id) {
		projects.remove(id);		
	}

	@Override
	public void removeType(int id) {
		types.remove(id);
	}

	@Override
	public void modifyProject(int projectId, Project newProject) {
		projects.set(projectId, newProject);
	}

	@Override
	public Project getProject(int projectId) {
		return projects.get(projectId);
	}

	@Override
	public List<Project> getProjects() {
		return projects;
	}

	@Override
	public Type getType(int typeId) {
		return types.get(typeId);
	}

	@Override
	public List<Type> getTypes() {
		return types;
	}

	@Override
	public void setProjectXMLPath(String path) {
		projectXMLPath = path;
		FileOutputStream fout = null;
		try {
			prop.setProperty("xmloutproject", path);
			fout = new FileOutputStream(new File(MyProperties.CONFIG_PATH));
			prop.storeToXML(fout, "");
		} catch (FileNotFoundException ex) {
			ex.printStackTrace();
		} catch (IOException ex) {
			ex.printStackTrace();
		} finally {
			if (fout != null){
				try {
					fout.close();
				} catch (IOException ex) {
					ex.printStackTrace();
				}
			}
		}
	}

	@Override
	public String getProjectXMLPath() {
		return projectXMLPath;
	}

	@Override
	public void setTypeXMLPath(String path) {
		typeXMLPath = path;
		FileOutputStream fout = null;
		try {
			prop.setProperty("xmlouttype", path);
			fout = new FileOutputStream(new File(MyProperties.CONFIG_PATH));
			prop.storeToXML(fout , "");
		} catch (FileNotFoundException ex) {
			ex.printStackTrace();
		} catch (IOException ex) {
			ex.printStackTrace();
		} finally {
			if (fout != null){
				try {
					fout.close();
				} catch (IOException ex) {
					ex.printStackTrace();
				}
			}
		}
	}

	@Override
	public String getTypeXMLPath() {
		return typeXMLPath;
	}

}
